package com.sky.service.user.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sky.constant.JwtClaimsConstant;
import com.sky.constant.MessageConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.exception.LoginFailedException;
import com.sky.mapper.admin.MerchantMapper;
import com.sky.mapper.user.UserMapper;
import com.sky.pojo.Merchant;
import com.sky.pojo.User;
import com.sky.properties.JwtProperties;
import com.sky.properties.WeChatProperties;
import com.sky.service.user.UserService;
import com.sky.utils.HttpClientUtil;
import com.sky.utils.JwtUtil;
import com.sky.utils.MapUtils;
import com.sky.vo.UserLoginVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

/**
 * 用户管理实现类
 */
@Service
public class UserServiceImpl implements UserService {
    public static final String WX_LOGIN = "https://api.weixin.qq.com/sns/jscode2session";
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private WeChatProperties weChatProperties;

    @Autowired
    private MerchantMapper merchantMapper;

    @Autowired
    private JwtProperties jwtProperties;

    /**
     * 用户登录
     *
     * @param userLoginDTO
     * @return
     */
    @Override
    public UserLoginVO userLogin(UserLoginDTO userLoginDTO) {
        // 发送微信返回openId
        String openId = getOpenId(userLoginDTO);
        if (openId == null) {
            throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
        }
        // 根据openId查询是否有该用户
        User user = userMapper.selectUser(openId);
        if (user == null) {
            // 第一次登录进行注册
            user = User.builder()
                    .openid(openId)
                    .createTime(LocalDateTime.now())
                    .build();
            userMapper.insertUser(user);
        }

        // 登录成功注册令牌
        Map<String, Object> claims = new HashMap<>();
        claims.put(JwtClaimsConstant.USER_ID, user.getId());
        String authentication = JwtUtil.createJWT(
                jwtProperties.getUserSecretKey(),
                jwtProperties.getUserTtl(),
                claims);

        // 查询商家信息
        Merchant merchant = merchantMapper.selectMerchant(1L);
        // 商家地址
        String addressLocation = MapUtils.addressToLnglat(merchant.getShopAddress());
        // 计算费用
        BigDecimal deliveryFee = MapUtils.getDelivoryCost(addressLocation, userLoginDTO.getLocation());
        UserLoginVO userLoginVO = UserLoginVO.builder()
                .openid(openId)
                .shopName(merchant.getShopName())
                .shopTelephone(merchant.getShopTelephone())
                .token(authentication)
                .shopId(1l)
                .shopAddress(merchant.getShopAddress())
                .id(user.getId())
                .deliveryFee(deliveryFee)
                .build();

        return userLoginVO;
    }

    private String getOpenId(UserLoginDTO userLoginDTO) {
        Map<String, String> map = new HashMap<>();
        map.put("appid", weChatProperties.getAppid());
        map.put("secret", weChatProperties.getSecret());
        map.put("js_code", userLoginDTO.getCode());
        map.put("grant_type", "authorization_code");
        String jsonStr = HttpClientUtil.doGet(WX_LOGIN, map);
        JSONObject jsonObject = JSON.parseObject(jsonStr);
        String openId = jsonObject.getString("openid");
        return openId;
    }
}
